//
//  JXChatManager.m
//  JiaoX
//
//  Created by yinqy on 15/3/12.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXChatManager.h"
#import "ForumDataTool.h"
#import "UserInfoDao.h"
#import "SelfDataTool.h"
#import <AVOSCloud/AVOSCloud.h>


static id instance = nil;
@interface JXChatManager()<AVSessionDelegate>
{
    AVSession *_session;
    NSMutableArray *_userIds;
}

@end
@implementation JXChatManager


+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken = 0;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init {
    if ((self = [super init])) {
        
        AVSession *session = [[AVSession alloc] init];
        session.sessionDelegate = self;
        _session = session;
        if (CURRENTUSERID) {
            [_session openWithPeerId:CURRENTUSERID];
        }
        _chatMsgDao = [[ChatMsgDao alloc]init];
        _userInfoDao = [[UserInfoDao alloc]init];
        _userIds = [NSMutableArray array];
    }
    return self;
}

-(void)openSession{
    if (![_session isOpen]) {
        if (CURRENTUSERID) {
            [_session openWithPeerId:CURRENTUSERID];
        }
    }
}

-(JXMessage *)imgMsgWithObjectId:(NSString *)objectId imgFile:(NSString *)imgFile toPeerId:(NSString *)toPeerId imgW:(CGFloat)imgW imgH:(CGFloat)imgH{
    JXMessage *imgMsg = [JXMessage imgMsgWithSession:_session objectId:objectId imgFile:imgFile toPeerId:toPeerId imgW:imgW imgH:imgH];
    //保存消息到数据库
    [_chatMsgDao insertMessage:imgMsg];
    //上传图片文件
    [self performSelectorInBackground:@selector(uploadFile:) withObject:imgMsg];
    return imgMsg;
}

/**
 *  在子线程中上传图片并发送消息
 *
 *  @param msg
 */
-(void)uploadFile:(JXMessage *)msg{
    NSData *data = [NSData dataWithContentsOfFile:msg.actualContent];
    AVFile *file = [AVFile fileWithData:data];
    BOOL saveResult = [file save];
    JXLog(@"file.url=%@",file.url);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:file.url forKey:@"fileurl"];
    [dic setObject:[NSNumber numberWithBool:saveResult] forKey:@"saveResult"];
    [dic setObject:msg forKey:@"message"];
    [self performSelectorOnMainThread:@selector(executeOnMainThread:) withObject:dic waitUntilDone:YES];
}

-(void)executeOnMainThread:(NSDictionary *)dic{
    BOOL saveResult = [[dic objectForKey:@"saveResult"] boolValue];
    NSString *fileurl = dic[@"fileurl"];
    JXMessage *msg = dic[@"message"];
    if (saveResult) {
        //上传成功，上传成功更新数据库图片路径并且删除保存在本地的图片
        NSString *fileDir = msg.actualContent;
        [msg setActualContent:fileurl];
        [_chatMsgDao setMessageContent:msg.messageId content:msg.payload];
        [_session sendMessage:msg];
        
        //删除本地文件
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSError *err;
        [fileMgr createDirectoryAtPath:fileDir withIntermediateDirectories:YES attributes:nil error:&err];
        if ([fileMgr fileExistsAtPath:fileDir]) {
            [fileMgr removeItemAtPath:fileDir error:nil];
        }
    }else{
        //上传失败，代表消息发送失败
        [self session:_session messageSendFailed:msg error:nil];
    }
}

/**
 * 是否watch了聊天用户
 */
-(BOOL)isWatchWithPeerId:(NSString *)peerId{
    if (![_session peerIdIsWatching:peerId]) {
        [self watchWithPeeId:peerId];
        return NO;
    }
    return YES;
}

-(void)watchWithPeeId:(NSString *)peerId{
    [_session watchPeerIds:@[peerId] callback:^(BOOL succeeded, NSError *error) {
        JXLog(@"watch result=%@",[NSNumber numberWithBool:succeeded]);
    }];
}

-(JXMessage *)sendMessageToPeerId:(NSString *)toPeerId messageStr:(NSString *)messageStr{
    [self isWatchWithPeerId:toPeerId];
    JXMessage *message = [JXMessage messageForPeerWithSession:_session toPeerId:toPeerId payload:messageStr];
    //添加到数据库
    [_chatMsgDao insertMessage:message];
    [_session sendMessage:message];
    return message;
}


/**
 * 得到签名
 */
-(void)getSignAndOpenSession{
    if (CURRENTUSERID) {
        [ForumDataTool getChatSignatureWithAppId:LEANCLOUD_APPID peerId:[UserDefaultsHelper stringForKey:KEY_USER_ID] success:^(ChatSignature *result) {
            if ([Utils isBlankString:result.data]) {
                [UserDefaultsHelper setObject:result.canSend forKey:KEY_CHAT_ENABLE];
            }
        } failure:^(NSError *error) {
        }];
        [self openSession];
    }
}

#pragma mark - AVSessionDelegate
- (void)session:(AVSession *)session didReceiveMessage:(AVMessage *)message{
    //收到消息了，应该怎么做
    JXLog(@"message.payload=%@",message.payload);
    //去watch一下
    [self isWatchWithPeerId:message.fromPeerId];
    //1.保存消息到数据库
    [_chatMsgDao insertMessage:[JXMessage fromAVMessage:message]];
    
    //判断一下有没有对方的个人信息，如果没有，则去查询。查询完成之后再发送通知界面更新
    if (![_userIds containsString:message.fromPeerId]) {
        if (![_userInfoDao getUserInfoWithId:message.fromPeerId]) {
            //数据库里面没有这个人的信息，去获取个人信息
            [SelfDataTool getUserInfoWithUserId:message.fromPeerId success:^(UserInfo *result) {
                if([Utils isBlankString:[result data]]){//获取用户信息成功
                    [_userInfoDao setUserInfo:result];
                    [_userIds addObject:message.fromPeerId];
                    [[JXChatManager sharedInstance].chatMsgDao addSessionWithId:result.userId type:RoomTypeSingle];
                    //2.调用代理通知界面更新
                    [self updateMessage:[JXMessage fromAVMessage:message] msgUpdateType:MsgUpdateTypeReceive];
                    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_UPDATA_BADGE_NUM object:nil];
                }
            } failure:^(NSError *error) {//获取用户信息失败
                JXLog(@"获取用户信息失败:%@",error);
            }];
        }else{
            //数据库有这个人的信息
            [_userIds addObject:message.fromPeerId];
            //2.调用代理通知界面更新
            [self updateMessage:[JXMessage fromAVMessage:message] msgUpdateType:MsgUpdateTypeReceive];
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_UPDATA_BADGE_NUM object:nil];
        }
    }else{
        //2.调用代理通知界面更新
        [self updateMessage:[JXMessage fromAVMessage:message] msgUpdateType:MsgUpdateTypeReceive];
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_UPDATA_BADGE_NUM object:nil];
    }
    
}
/*!
 *  消息发送成功
 *  回调表示消息已经成功发送到服务器
 */
- (void)session:(AVSession *)session messageSendFinished:(JXMessage *)message{
    JXLog(@"这条消息发送成功了。message=%@",message.payload);
    //更新这条消息的发送状态。
    [message setSendStatus:StatusSendSucceed];
    [_chatMsgDao setMessageSendStatus:message.messageId sendStatus:StatusSendSucceed];
    
    //调用代理通知界面更新
    [self updateMessage:message msgUpdateType:MsgUpdateTypeSend];
}

-(void)session:(AVSession *)session messageSendFailed:(JXMessage *)message error:(NSError *)error{
    JXLog(@"这条消息发送失败了。message=%@",message.payload);
    [message setSendStatus:StatusSendFailed];
    [_chatMsgDao setMessageSendStatus:message.messageId sendStatus:StatusSendFailed];
    //调用代理通知界面更新
    [self updateMessage:message msgUpdateType:MsgUpdateTypeSend];
}

-(void)updateMessage:(JXMessage *)message msgUpdateType:(MsgUpdateType)type{
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:message, @"message", [NSNumber numberWithInt:type], @"MsgUpdateType", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_NEW_MESSAGE object:dic];
}

-(void)unWatchWithPeerId:(NSString *)toPeerId{
    [_session unwatchPeerIds:@[toPeerId] callback:^(BOOL succeeded, NSError *error) {
        JXLog(@"unwatch result=%@",[NSNumber numberWithBool:succeeded]);
    }];
}

@end
